iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 26
0
Modern Web

用30days 了解web系列 第 26

(Day 26) create your first Docker application

  • 分享至 

  • xImage
  •  

Now that you know what Docker is, it’s time to create your first application!
The purpose of this short tutorial is to create a Python program that displays a sentence. This program will have to be launched through Dockerfile.
You will see, it’s not very complicated once you understand the process.

Note: You will not need to install Python on your computer. It will be up to the Docker environment to contain Python in the aim of executing your code.

Install Docker on your machine
For Ubuntu:
First, update your packages:
$ sudo apt update
Next, install docker with apt-get:
$ sudo apt install docker.io
Finally, verify that Docker is installed correctly:
$ sudo docker run hello-world

Create your project
To create your first Docker application, I invite you to create a folder on your computer. It must contain the following two files:

  • A ‘main.py’ file (python file that will contain the code to be executed).
  • A ‘Dockerfile’ file (Docker file that will contain the necessary instructions to create the environment).

you can use vim to create the main.py and Dockerfile

Edit the Python file
use vim to write your main.py:

print("Hello Docker")

Edit the Docker file
edit your Dockerfile

# A dockerfile must always start by importing the base image.
# We use the keyword 'FROM' to do that.
# In our example, we want import the python image.
# So we write 'python' for the image name and 'latest' for the version.
FROM python:latest

# In order to launch our python code, we must import it into our image.
# We use the keyword 'ADD' to do that.
# The first parameter 'main.py' is the name of the file on the host.
# The second parameter '/' is the path where to put the file on the image.
# Here we put the file at the image root folder.
ADD main.py /

# We need to define the command to launch when we are going to run the image.
# We use the keyword 'CMD' to do that.
# The following command will execute "python ./main.py".
CMD [ "python", "./main.py" ]

Create the Docker image
Once your code is ready, and the Dockerfile is written, all you have to do is create your image to contain your application.
$ docker build -t python-test
The ’-t’ option allows you to define the name of your image. In our case, we have chosen ’python-test’ but you can put what you want.

Run the Docker image
Once the image is created, your code is ready to be launched.
$ docker run python-test
You need to put the name of your image after ‘docker run’.
There you go, that’s it. You should see “Hello Docker” displayed in your terminal.


上一篇
(Day 25) Docker vs Virtual Machine
下一篇
(day 27) Secure your docker container
系列文
用30days 了解web30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言